package com.xxx.baseapplication

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.View
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import com.xxx.baseapplication.databinding.ActivityWebBinding
import com.xxx.baseapplication.util.WebViewUtil
import com.xxx.baseapplication.vm.WebVM
import com.xxx.baseapplication.web.WanObject
import com.xxx.baseapplication.web.WebViewClientFactory
import com.xxx.mylibrary.base.BaseActivity
import com.xxx.mylibrary.binds.arg
import com.xxx.mylibrary.binds.viewModel
import com.xxx.mylibrary.widget.WanWebView
import io.github.iamyours.router.annotation.Route

@Route(path = "/web")
class WebActivity : BaseActivity<ActivityWebBinding>() {
    companion object {
        fun nav(link: String, context: Context) {
            val intent = Intent(context, WebActivity::class.java)
            intent.putExtra("link", link)
            if (context is Activity) {
                context.startActivityForResult(intent, 1)
            }
        }
    }


    override val layoutId: Int
        get() = R.layout.activity_web

    val link by arg<String>("link")
    val vm by viewModel<WebVM>()
    var navTitle = ""

    override fun onEnterAnimationComplete() {
        super.onEnterAnimationComplete()
        binding.showImage.visibility = View.INVISIBLE
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding.vm = vm
        initWebView()
        binding.showImage.setDisableTouch(true)
    }


    private fun initWebView() {
        binding.webView.settings.run {
            javaScriptEnabled = true
            domStorageEnabled = true
            databaseEnabled = true
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
            }
        }

        binding.webView.run {
            WebViewUtil.fixWebView(this)
            setBackgroundColor(0)
            loadWeb(this, link)
            webViewClient = WebViewClientFactory.create(link!!, vm.loaded)
            webChromeClient = object : WebChromeClient() {
                override fun onReceivedTitle(view: WebView?, t: String?) {
                    super.onReceivedTitle(view, t)
                    navTitle = t ?: ""
                }
            }

            addJavascriptInterface(
                WanObject(this@WebActivity, vm.image),
                "android"
            )

            scrollListener = object : WanWebView.OnScrollChangedListener {
                override fun onScroll(dx: Int, dy: Int, oldX: Int, oldY: Int) {
                    vm.title.value = if (dy < 10) "" else navTitle
                }
            }

            checkHeightHandler.sendEmptyMessageDelayed(1, 60)
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(BuildConfig.DEBUG)
        }

    }

    private var checkHeightHandler = @SuppressLint("HandlerLeak")
    object : Handler() {
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            if (vm.loaded.value == true) {
                return
            }
            checkWebHeight()
            sendEmptyMessageDelayed(1, 60)
        }
    }

    private fun checkWebHeight() {//检查内容高度，隐藏加载进度
        binding.webView.run {
            if (contentHeight > height / 2) {
                vm.loaded.value = true
            }
        }
    }

    private fun loadWeb(webview: WanWebView, url: String?) {
        webview.loadUrl(url)
    }
}